﻿using LSL.SqlClient;
using System;
using System.Collections.Generic;

namespace Liu_Project.Utils
{
    public static class ExpressionMethod
    {
        /// <summary>
        /// 获取SQL查询条件
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="param">可自定义,传查询条件参数的名称,默认：DataWhere</param>
        /// <returns></returns>
        public static string GetSqlWhere(System.Web.HttpContext context, string paramName = "DataWhere")
        {
            var DataWhere = DataConvert.ToString(context.Request[paramName], "[]");
            var querys = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Query>>(DataWhere);
            string strWhere = GetWhereByQuery(querys);
            return strWhere;
        }

        
        public static string GetWhereByQuery(List<Query> querys)
        {
            if (querys == null)
                return "";

            System.Text.StringBuilder sbWhere = new System.Text.StringBuilder();
            querys.ForEach(delegate (Query q)
            {
                sbWhere.Append(q.Logic);
                int index = 1;
                string[] fileIds = q.Field.Split(',');
                if (q.IsNoSubField)
                    fileIds = new string[] { q.Field };

                foreach (var fileId in fileIds)
                {
                    string Value = DataConvert.ToString(q.Value, "");
                    Value = Value.Trim();
                    switch (q.Method.ToLower())
                    {
                        case ExpressionSqlMethod.Contains:
                            Value = "'%" + Value + "%'";
                            break;
                        case ExpressionSqlMethod.In:
                            if (!Value.StartsWith("'"))
                            {
                                Value = Value.Replace(",", "','");
                                Value = "('" + Value + "')";
                            }
                            break;
                        case ExpressionSqlMethod.NotIn:
                            if (!Value.StartsWith("'"))
                            {
                                Value = Value.Replace(",", "','");
                                Value = "('" + Value + "')";
                            }
                            break;
                        case ExpressionSqlMethod.Exists:
                            break;
                        default:
                            Value = "'" + Value + "'";
                            break;
                    }

                    string Method = q.Method;
                    if (Method == ExpressionSqlMethod.Contains)
                    {
                        Method = "LIKE";
                    }

                    if (Method == ExpressionSqlMethod.NotIn)
                    {
                        Method = "NOT IN";
                    }

                    string Field = fileId;
                    if (!fileId.Contains(".") && !q.IsNoSubField)
                        Field = "[" + fileId + "]";

                    if (Method.ToUpper() == "EXISTS")
                    {
                        //if (fileIds.Length > 1)
                        //{
                        //    if (index == 1)
                        //        sbWhere.AppendFormat(" ( EXISTS (SELECT 1 FROM {1} ET WHERE ET.ID = {0})", Field, Value);
                        //    else
                        //        sbWhere.AppendFormat(" {0} EXISTS(SELECT 1 FROM {2} ET WHERE ET.ID = {1}) ", q.SubLogic, Field, Value);
                        //    if (fileIds.Length == index)
                        //        sbWhere.Append(")");
                        //}
                        //else
                        //    sbWhere.AppendFormat(" EXISTS (SELECT 1 FROM {1} ET WHERE ET.ID = {0})", Field, Value);
                    }
                    else
                    {
                        if (fileIds.Length > 1)
                        {
                            if (index == 1)
                                sbWhere.AppendFormat(" ({0} {1} {2}", Field, Method, Value);
                            else
                                sbWhere.AppendFormat(" {0} {1} {2} {3} ", q.SubLogic, Field, Method, Value);
                            if (fileIds.Length == index)
                                sbWhere.Append(")");
                        }
                        else
                            sbWhere.AppendFormat(" {0} {1} {2} ", Field, Method, Value);
                    }
                    index++;
                }
            });

            return sbWhere.ToString();
        }
    }
    public class Query
    {
        
        public string Logic { get; set; }
        public string Field { get; set; }
        
        public string Method { get; set; }
        public object Value { get; set; }
        
        public string SubLogic { get; set; }
        
        public bool IsNoSubField { get; set; }

    }

    public class ExpressionSqlMethod
    {
        public const string Contains = "%";
        public const string GreaterThan = ">";
        public const string LessThan = "<";
        public const string GreaterThanOrEqual = ">=";
        public const string LessThanOrEqual = "<=";
        public const string Equal = "=";
        public const string NotEqual = "<>";
        public const string In = "in";
        public const string NotIn = "notin";
        public const string Exists = "exists";
    }
}
